import 'package:stacked/stacked.dart';
import '../heartbeat/blueprint/follow_model.dart';

/// 关注管理器
class FollowManager extends BaseViewModel {
  // 关注关系列表
  final List<FollowRelationModel> _relations = [];

  /// 获取所有关注关系
  List<FollowRelationModel> get relations => List.from(_relations);

  /// 初始化默认关注数据
  void initializeDefaultFollows() {
    _relations.clear();
    _relations.addAll(_getDefaultFollows());
  }

  /// 获取默认关注数据
  List<FollowRelationModel> _getDefaultFollows() {
    return [
      // admin用户（ID: 1）关注其他用户
      FollowRelationModel(
        id: '1',
        followerId: '1', // admin
        followingId: '2', // Nexus
        createdAt: DateTime.now().subtract(const Duration(days: 10)),
      ),
      FollowRelationModel(
        id: '2',
        followerId: '1', // admin
        followingId: '3', // Vortex
        createdAt: DateTime.now().subtract(const Duration(days: 8)),
      ),
      FollowRelationModel(
        id: '3',
        followerId: '1', // admin
        followingId: '4', // Prism
        createdAt: DateTime.now().subtract(const Duration(days: 6)),
      ),
      FollowRelationModel(
        id: '4',
        followerId: '1', // admin
        followingId: '5', // Cipher
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),
      FollowRelationModel(
        id: '5',
        followerId: '1', // admin
        followingId: '6', // Quantum
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),

      // 其他用户关注admin用户
      FollowRelationModel(
        id: '6',
        followerId: '2', // Nexus
        followingId: '1', // admin
        createdAt: DateTime.now().subtract(const Duration(days: 9)),
      ),
      FollowRelationModel(
        id: '7',
        followerId: '3', // Vortex
        followingId: '1', // admin
        createdAt: DateTime.now().subtract(const Duration(days: 7)),
      ),
      FollowRelationModel(
        id: '8',
        followerId: '4', // Prism
        followingId: '1', // admin
        createdAt: DateTime.now().subtract(const Duration(days: 5)),
      ),
      FollowRelationModel(
        id: '9',
        followerId: '5', // Cipher
        followingId: '1', // admin
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      FollowRelationModel(
        id: '10',
        followerId: '6', // Quantum
        followingId: '1', // admin
        createdAt: DateTime.now().subtract(const Duration(days: 1)),
      ),

      // 其他用户之间的关注关系
      FollowRelationModel(
        id: '11',
        followerId: '2', // Nexus
        followingId: '3', // Vortex
        createdAt: DateTime.now().subtract(const Duration(days: 6)),
      ),
      FollowRelationModel(
        id: '12',
        followerId: '3', // Vortex
        followingId: '2', // Nexus
        createdAt: DateTime.now().subtract(const Duration(days: 5)),
      ),
      FollowRelationModel(
        id: '13',
        followerId: '4', // Prism
        followingId: '5', // Cipher
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),
      FollowRelationModel(
        id: '14',
        followerId: '5', // Cipher
        followingId: '6', // Quantum
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      FollowRelationModel(
        id: '15',
        followerId: '6', // Quantum
        followingId: '7', // Matrix
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
    ];
  }

  /// 关注用户
  Future<bool> establishFollow({
    required String followerId,
    required String followingId,
  }) async {
    setBusy(true);
    try {
      // 检查是否已经关注
      if (isFollowing(followerId, followingId)) {
        setError('You are already following this user');
        return false;
      }

      // 不能关注自己
      if (followerId == followingId) {
        setError('You cannot follow yourself');
        return false;
      }

      // 创建关注关系
      final relation = FollowRelationModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        followerId: followerId,
        followingId: followingId,
        createdAt: DateTime.now(),
      );

      _relations.add(relation);
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 取消关注
  Future<bool> terminateFollow({
    required String followerId,
    required String followingId,
  }) async {
    setBusy(true);
    try {
      // 查找关注关系
      final relationIndex = _relations.indexWhere(
        (relation) =>
            relation.followerId == followerId &&
            relation.followingId == followingId,
      );

      if (relationIndex == -1) {
        setError('Follow relation not found');
        return false;
      }

      // 删除关注关系
      _relations.removeAt(relationIndex);
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 检查是否已关注
  bool isFollowing(String followerId, String followingId) {
    return _relations.any(
      (relation) =>
          relation.followerId == followerId &&
          relation.followingId == followingId,
    );
  }

  /// 获取用户的关注列表
  List<FollowRelationModel> fetchFollowingList(String userId) {
    return _relations
        .where((relation) => relation.followerId == userId)
        .toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  /// 获取用户的粉丝列表
  List<FollowRelationModel> fetchFollowersList(String userId) {
    return _relations
        .where((relation) => relation.followingId == userId)
        .toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  /// 获取关注数量
  int getFollowingCount(String userId) {
    return _relations.where((relation) => relation.followerId == userId).length;
  }

  /// 获取粉丝数量
  int getFollowersCount(String userId) {
    return _relations
        .where((relation) => relation.followingId == userId)
        .length;
  }
}
